import { Subject, Subscription, take } from 'rxjs';

import { _decorator } from 'cc';

const { ccclass } = _decorator;

export class ReactiveCommand<T> {

    static Create<T>(): ReactiveCommand<T> {
        return new ReactiveCommand<T>().init();
    }

    _subject: Subject<T> = null;

    init(): ReactiveCommand<T> {
        this._subject = new Subject();
        return this;
    }

    execute(param?: T) {
        this._subject.next(param);
    }

    subscribe(callback: (param?: T) => void): Subscription {
        return this._subject.subscribe(callback);
    }

    subscribeOnce(callback: (param?: T) => void): Subscription {
        return this._subject.pipe(take(1)).subscribe(callback);
    }
}
